package com.kds.changzhou.utility;

import com.kds.changzhou.dao.RedisCache;
import com.kds.changzhou.data.Function;
import com.kds.changzhou.data.Gateway;
import com.kds.changzhou.data.Report;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 孔德嵩
 */
@Component
@Slf4j
public class DataQueryService {

    private static final String REDIS_KEY = "building_energy:data";
    private static final String complexExpression = "^\\[.*\\]$";

    private static final String pattern = "\\w+_\\d+_\\d+_\\d+";
    // 创建 Pattern 对象
    private Pattern expressionPattern;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ExpressionEvaluation evaluation;

    {
        expressionPattern = Pattern.compile(pattern);
    }


    public Report makeReport(Gateway gateway) throws Exception {


        Report report = buildReportByGateway(gateway);
        report.setSequence(gateway.getSequence());
        report.setTime(reportTime(new DateTime()).toDate());

        return report;
    }


    private Report buildReportByGateway(Gateway gateway) {

        Map<String, Double> values = redisCache.getAllData();

        Report report = new Report();

        report.setBuildingCode(gateway.getBuildingCode());

        report.setGatewayId(gateway.getGatewayId());

        Collection<Function> functions = gateway.getFunctions();

        report.setFunctions(functions);

        for (Function function : functions) {

            String expression = function.getExpression();

            Double _v = handleExpression(expression, values);

            Double value = _v == null ? 0 : _v;

            function.setValue(value);
        }
        return report;
    }


    private Double handleExpression(String expression, Map<String, Double> values) {

        if (isSimpleExpression(expression)) {

            return values.get(expression);
        } else {

            return figureComplexExpression(expression, values);
        }
    }

    private boolean isSimpleExpression(String expression) {

        // 使用 matches 方法判断是否匹配
        return !expression.matches(complexExpression);

    }


    private Double figureComplexExpression(String expression, Map<String, Double> values) {


        // 创建 matcher 对象
        Matcher matcher = expressionPattern.matcher(expression);


        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String fid = matcher.group();
            Double value = values.get(fid);
            if (value == null) {
                value = 0D;
            }
            matcher.appendReplacement(sb, String.valueOf(value));
        }

        matcher.appendTail(sb);

        return evaluation.evaluateExpression(sb);
    }


    private DateTime reportTime(DateTime originalDateTime) {

        int minute = originalDateTime.getMinuteOfHour();
        int newMinute = minute - minute % 15; // 计算归整后的分钟数
        DateTime roundedDateTime = originalDateTime.withMinuteOfHour(newMinute).withSecondOfMinute(0).withMillisOfSecond(0);
        log.debug("归整后时间: {}", roundedDateTime);
        return roundedDateTime;

    }


}
